package com.mfn.sportjava.knowledge.model;

import com.baomidou.mybatisplus.annotation.*; // 新增导入
import com.mfn.sportjava.model.dto.MatchDTO;
// 移除 jakarta.persistence.* 的导入
import lombok.Data;
import lombok.NoArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;

/**
 * 存储在MySQL数据库中的知识条目
 * @author Anyang
 * @version 1.0.1
 * @date 2025/05/18
 */
@Data
@NoArgsConstructor
@TableName("knowledge_entries")
public class KnowledgeEntry {
    private static final Logger log = LoggerFactory.getLogger(KnowledgeEntry.class);

    @TableId(type = IdType.AUTO)
    private Long id;

    /**
     * 表示比赛的唯一键（"league_home_away_date"）。
     * 用于快速查找。根据MatchDTO生成。
     * 数据库层面应有唯一约束。
     */
     @TableField("match_key")
    private String matchKey;

     @TableField("league")
    private String league;

     @TableField("home_team")
    private String homeTeam;

     @TableField("away_team")
    private String awayTeam;

    /**
     * 大文本内容，与比赛相关的实际文本知识内容。用于增强AI提示。
     */
    @TableField("content")
    private String content;

    @TableField(fill = FieldFill.INSERT)
    private LocalDateTime createdAt;

    @TableField(fill = FieldFill.INSERT_UPDATE)
    private LocalDateTime updatedAt;

    public KnowledgeEntry(String matchKey, String league, String homeTeam, String awayTeam, String content) {
        this.matchKey = matchKey;
        this.league = league;
        this.homeTeam = homeTeam;
        this.awayTeam = awayTeam;
        this.content = content;
    }

    /**
     * 用于生成一致的比赛键的辅助方法。
     * 格式: LEAGUE_HOMETEAM_AWAYTEAM_DATE
     * @param match MatchDTO对象。
     * @return 生成的比赛键字符串。
     */
    public static String generateMatchKey(MatchDTO match) {
        if (match == null) {
            log.warn("MatchDTO 为 null，无法生成 matchKey。");
            return "INVALID_MATCH_KEY_NULL_DTO";
        }
        String normLeague = normalize(match.getLeague());
        String normDate = normalize(match.getDate());

        String[] teams = parseTeamsFromMatchStringStatic(match.getMatch());
        if (teams != null && teams.length == 2) {
            String normHomeTeam = normalize(teams[0]);
            String normAwayTeam = normalize(teams[1]);
            return String.format("%s_%s_%s_%s", normLeague, normHomeTeam, normAwayTeam, normDate)
                    .toUpperCase().replaceAll("\\s+", "_");
        } else {
            log.warn("无法从比赛字符串 '{}' (联赛: {}, 日期: {}) 解析主客队，matchKey 可能不规范或不唯一。",
                    match.getMatch(), match.getLeague(), match.getDate());
            String fallbackMatchPart = normalize(match.getMatch())
                    .replaceAll("\\s*vs\\.?\\s*", "_VS_") // 匹配 "vs", "vs.", "VS" 等
                    .replaceAll("[^a-zA-Z0-9_]", "") // 移除非字母数字下划线字符
                    .replaceAll("\\s+", "_");
            return String.format("%s_%s_%s", normLeague, fallbackMatchPart, normDate)
                    .toUpperCase();
        }
    }

    private static String normalize(String input) {
        return (input == null || input.isBlank()) ? "unknown" : input.trim().toLowerCase();
    }

    private static String[] parseTeamsFromMatchStringStatic(String matchString) {
        if (matchString == null || matchString.isBlank()) {
            return null;
        }
        String[] parts = matchString.split("\\s*[vV][sS]\\.?\\s*", 2);
        if (parts.length == 2) {
            String homeTeam = parts[0].trim();
            String awayTeam = parts[1].trim();
            if (!homeTeam.isEmpty() && !awayTeam.isEmpty()) {
                return new String[]{homeTeam, awayTeam};
            }
        }
        return null;
    }
}
